#!/usr/bin/env python3
# encoding: utf-8

"""
@version: 1.0
@author: 周永波
@file: val.py
@time: 2020/7/18 14:53
"""
from _ast import Tuple

from django.http.response import HttpResponseBase, JsonResponse
from django.utils.deprecation import MiddlewareMixin

from result.ResultInfo import ResultInfo
from result.RetException import RetException


class ReturnValHandler(MiddlewareMixin):

    def process_request(self, request):
        print("md1  process_request 方法。", id(request))  # 在视图之前执行
        print("1")
        pass

    def process_response(self, request, response):
        # 基于请求响应
        # print("md1  process_response 方法！", id(request))  # 在视图之后
        if isinstance(response, HttpResponseBase):
            return response

        ret:ResultInfo = None
        if type(response) is Tuple:
            if len(response) == 1:
                if type(response[0]) is not int:
                    ret = ResultInfo.success(response[0])
                else:
                    ret = ResultInfo(response[0], response[1], None)
            elif len(response) == 2:
                ret = ResultInfo(response[0], response[1], None)
            else:
                ret = ResultInfo(response[0], response[1], response[2])
        else:
            ret = ResultInfo(100, None, response)

        return JsonResponse(ret.__dict__, safe=False, json_dumps_params={'ensure_ascii': False})

    def process_exception(self, request, exception):  # 引发错误 才会触发这个方法
        print("md1  process_exception 方法！")
        if isinstance(exception,RetException):
             ret = ResultInfo.error(exception.code, exception.message)
             return JsonResponse(ret.__dict__, safe=False)
        # print("md1  process_exception 方法！")
        # return HttpResponse(exception) #返回错误信息

class login(MiddlewareMixin):

    def process_request(self, request):
        print(" ------------- login ---- ")
        pass
